package com.google.bitcoin.examples;

import com.google.bitcoin.core.*;
import com.google.common.base.Preconditions;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Helper class to serialize requests to remote multikey holders
 * todo more elegant serialisation for byte[] than default GSON
 * @author apetersson
 */
public class MultisigRequest {
    final Sha256Hash hashToSign;
    final PubKey pubKeyToUse;
    final byte[] transactionBytes;
    final byte[] connectedPubKeyScript;
    final int inputIndex;


    public MultisigRequest(Sha256Hash hashToSign, PubKey pubKeyToUse, Transaction toSign, NetworkParameters networkParameters, int inputIndex) {
        this.hashToSign = hashToSign;
        this.pubKeyToUse = pubKeyToUse;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            new BitcoinSerializer(networkParameters, true).serialize(toSign, bos);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        transactionBytes = bos.toByteArray();
        //note: in reality, this should not be needed. rather, toSign should have a problem-specific serializer (to Json or whatever)
        connectedPubKeyScript = Preconditions.checkNotNull(toSign.getInputs().get(inputIndex).getOutpoint().getConnectedPubKeyScript());
        Preconditions.checkNotNull(transactionBytes);
        this.inputIndex = inputIndex;
    }
}
